/*
 * StdVariableModule.cpp
 *
 *  Created on: 01.08.2009
 *      Author: h3llfire
 */

#include "StdVariableModule.h"
#include <wx/regex.h>
#include <wx/log.h>

namespace Impp {

IMPLEMENT_DYNAMIC_CLASS(StdVariableModule, iModule);


StdVariableModule::StdVariableModule() {
}

StdVariableModule::~StdVariableModule() {
}

void StdVariableModule::moduleInit(){}


wxString StdVariableModule::parseString(const wxString& varString){
	//wxLogDebug(wxT("search: %s"), varString.c_str());

	wxString ret;

	wxRegEx reg(wxT("\\$\\{([^\\}]+)\\}"),wxRE_ADVANCED|wxRE_ICASE);

	const wxChar* toLook = varString.GetData();
	size_t lng = varString.length();

	while(reg.Matches(toLook,wxRE_NOTBOL|wxRE_NOTEOL,lng)){

		wxString match = reg.GetMatch(toLook, 1);
		size_t mstart, mlng;
	    reg.GetMatch(&mstart,&mlng,0);

	    //wxLogDebug(wxT("match %s"), match.c_str());

	    if(mstart!=0){
	    	ret << wxString(toLook,mstart);
	    }

	    ret << getVarValue(match);

	    size_t offset = mstart + mlng;
	    toLook+=offset;
	    lng -= offset;
	}

	if(lng!=0){
		ret << wxString(toLook,lng);
	}
	return ret;
}

void StdVariableModule::setVar(const wxString& name, const wxString& value){
	std::vector<Variable>::iterator i(vars.begin());
	for(; i < vars.end(); i++){
		if(i->name == name){
			i->value = value;
			return;
		}
	}
	vars.push_back(Variable(name, value));
}

wxString StdVariableModule::getVarValue(const wxString& name){
	std::vector<Variable>::iterator i(vars.begin());
	for(; i < vars.end(); i++){
		if(i->name == name){
			return i->value;
		}
	}
	return wxEmptyString;
}


}
